//
//  HWTakeALookDetailController.swift
//  PlayWithProject
//
//  Created by 王昌健 on 2021/8/3.
//

import UIKit
import ZLPhotoBrowser
import IQKeyboardManagerSwift
class HWTakeALookDetailController: HWBaseViewController {
    
    var collectionView:UICollectionView!
    
    var keyboardView:HWCommentKeyboardView!
    
    var model:HWGameCircleModel?
    
    var superVCLive_uid = ""
    
    var is_look = ""
    let httpManager = HWGameCircleHttpManager()
//    let userHttpManager = HWUserInfoHttpManager()
    let collectionProtocol = HWTakeALookDetailProtocol()
    let mutDataArr = NSMutableArray()
    
    /// 评论回复传过来的评论model
    var replyModel:HWTakeALookCommentModel?
    
    var navMoreButton:UIButton!
    var detailModel:HWGameCircleModel?
    var deteleBlock:(() -> Void)?
    var likeBlock:(() -> Void)?
    
    var tempBgView:UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
        loadData()
        
        addAction()
        
        addRefresh()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = false
        IQKeyboardManager.shared.shouldToolbarUsesTextFieldTintColor = false
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.shouldToolbarUsesTextFieldTintColor = true
    }
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        IQKeyboardManager.shared.enable = false
//        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
//        IQKeyboardManager.shared.enableAutoToolbar = false
//
//    }
//
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//        IQKeyboardManager.shared.enable = true
//        IQKeyboardManager.shared.enableAutoToolbar = true
//        IQKeyboardManager.shared.shouldResignOnTouchOutside = false
//    }
}

extension HWTakeALookDetailController {
    private func initUI() -> Void {
        navigationView.titleLabel.text = "详情"
        navigationView.backButton.setImage(UIImage(named: "fanhui"), for: .normal)
        navigationView.backgroundColor = .white
        navMoreButton = UIButton(type: .custom)
        navMoreButton.setImage(UIImage(named: "fanxiangdeicotupian"), for: .normal)
        navMoreButton.addTarget(self, action: #selector(navMoreButtonClick), for: .touchUpInside)
        navigationView.addSubview(navMoreButton)
        
        let flowL = HWTakeALookDetailCommentFlowLayout.init()
        //        flowL.estimatedItemSize = CGSize(width: 10, height: 10)
        flowL.minimumLineSpacing = 0
        flowL.minimumInteritemSpacing = 0
        //        flowL.decorationDelegate = collectionProtocol
        
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: flowL)
        collectionView.delegate = collectionProtocol
        collectionView.dataSource = collectionProtocol
        collectionView.backgroundColor = .white
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(HWGameCircleCell.self, forCellWithReuseIdentifier: "HWGameCircleCell")
        collectionView.register(HWTakeALookPageHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HWTakeALookPageHeader")
        collectionView.register(HWTakeALookPageFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "HWTakeALookPageFooter")
        
        collectionView.register(HWTakeALookDetailCommentHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HWTakeALookDetailCommentHeader")
        collectionView.register(HWTakeALookDetailCommentCell.self, forCellWithReuseIdentifier: "HWTakeALookDetailCommentCell")
        collectionView.register(HWTakeALookDetailCommentFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "HWTakeALookDetailCommentFooter")
        view.addSubview(collectionView)
        
        
        tempBgView = UIView.init()
        tempBgView.backgroundColor = UIColor.clear
        tempBgView.isHidden = true
        view.addSubview(tempBgView)
        
        keyboardView = HWCommentKeyboardView()
        view.addSubview(keyboardView)
        //        UIApplication.shared.windows.filter({$0.isKeyWindow}).last?.rootViewController?.view.addSubview(keyboardView)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrameNotify(_:)), name:UIResponder.keyboardWillChangeFrameNotification, object: nil)
        
        let tapBg = UITapGestureRecognizer.init(target: self, action: #selector(closeKeyboard))
        tempBgView.addGestureRecognizer(tapBg)
    }
    
    private func initFrame() -> Void {
        
        navMoreButton.snp.makeConstraints { make in
            make.centerY.equalTo(navigationView.titleLabel)
            make.right.equalTo(-15*widthScale)
            make.width.equalTo(25*widthScale)
            make.height.equalTo(5*widthScale)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(navigationView.snp.bottom)
            make.bottom.equalTo(-88)
        }
        
        tempBgView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalTo(0)
            
        }
        
        keyboardView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            //            make.bottom.equalTo(-34)
            if #available(iOS 11, *){
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            }else{
                make.bottom.equalTo(0)
            }
        }
    }
}

extension HWTakeALookDetailController{
    
    func addRefresh() -> () {
        
        collectionView.mj_header = MJRefreshNormalHeader()
        collectionView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        collectionView.mj_footer = MJRefreshBackNormalFooter()
        collectionView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        
        self.httpManager.getTakeALookCommentListFooter(id: model?.id ?? "") { modelArr in
            self.collectionView.mj_footer?.endRefreshing()
            if modelArr.count > 0 {
                self.mutDataArr.addObjects(from: modelArr)
            }
            self.collectionProtocol.commentModels = self.mutDataArr as? [HWTakeALookCommentModel]
            self.collectionView.reloadData()
        } failure: { error in
            if error == "没有更多了"{
                self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            }else{
                self.collectionView.mj_footer?.endRefreshing()
            }
        }
        
    }
    
    
    
    func loadData() -> Void {
        httpManager.getTakeALookDetailData(id: model?.id ?? "",is_look: is_look) { model in
            self.detailModel = model
            self.collectionProtocol.model = model
            self.collectionView.reloadData()
        } failure: { error in
            
        }
        
        httpManager.getTakeALookCommentList(id: model?.id ?? "") { models in
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.mutDataArr.removeAllObjects()
                self.mutDataArr.addObjects(from: models)
            }
            self.collectionProtocol.commentModels = self.mutDataArr as? [HWTakeALookCommentModel]
            self.collectionView.reloadData()
        } failure: { error in
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
        
//        userHttpManager.getUserIsFollow(live_uid: model?.live_uid ?? "") { isFollow in
//
//            if isFollow == 1 {
//                self.followButton.setTitle("已关注", for: UIControl.State.normal)
//            }else{
//                self.followButton.setTitle("关注", for: UIControl.State.normal)
//            }
//        } failure: { error in
//
//        }
        
    }
    
    
    
}


extension HWTakeALookDetailController {
    @objc func followButtonClick(_ button:UIButton) -> Void {
//        userHttpManager.getUserSetFollow(live_uid: model?.live_uid ?? "") { success in
////                self.view.showHUD(title: success)
//            self.loadData()
//        } failure: { error in
////                self.view.showHUD(title: error)
//        }
    }
    func addAction() -> Void {
        
        
        collectionProtocol.didSelectImage = {
            index,images in
            var datas: [Any] = []
            for a in images {
                datas.append(URL(string: a)!)
            }
            let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false) { (url) -> ZLURLType in
                
                return .image
            } urlImageLoader: { (url, imageView, progress, loadFinish) in
                imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                    let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                    debugPrint("\(percentage)")
                    progress(percentage)
                } completionHandler: { (_) in
                    loadFinish()
                }
            }
            
            vc.doneBlock = { (datas) in
                debugPrint(datas)
            }
            
            vc.modalPresentationStyle = .fullScreen
            self.showDetailViewController(vc, sender: nil)
            
        }
        
        collectionProtocol.didSelectVideo = {
            url in
               
            let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
                return .video
            } urlImageLoader: { (url, imageView, progress, loadFinish) in
                imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                    let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                    debugPrint("\(percentage)")
                    progress(percentage)
                } completionHandler: { (_) in
                    loadFinish()
                }
            }
            
            vc.doneBlock = { (datas) in
                debugPrint(datas)
            }
            vc.modalPresentationStyle = .fullScreen
            self.showDetailViewController(vc, sender: nil)
        }
        
        
        collectionProtocol.zanButtonClick = {
            type,id in
            if HWLocallyStoredData.getLoginUserID().count>0{
                self.httpManager.setTakeALookZan(type: type, id: id) { message in
                    self.is_look = "1"
                    self.loadData()
                    self.likeBlock?()
                } failure: { error in
                    
                }
            }else{
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
            }
            
            
        }
        
        collectionProtocol.jumpToDetail = {
            id in
 
        }
        
        collectionProtocol.jumpToUserDetail = {
            if self.superVCLive_uid == $0 {
                
            }else{
//                let userDetailControler = HWUserDetailController()
//                userDetailControler.live_uid = $0
//                self.navigationController?.pushViewController(userDetailControler, animated: true)
            }
            
        }
        
        collectionProtocol.jumpToCommentDetail = {
            let commentDetailVC = HWTakeALookCommentDetailController()
            commentDetailVC.donttai_id = self.model?.id ?? ""
            commentDetailVC.superCommentModel = $0
            self.navigationController?.pushViewController(commentDetailVC, animated: true)
        }
        
        collectionProtocol.replyContentName = {
            self.replyModel = $0
            self.keyboardView.textField.placeholder = "回复：" + $0.pet_name
            self.keyboardView.textField.becomeFirstResponder()
        }
        
        keyboardView.sendText = {
            if HWLocallyStoredData.getLoginUserID().count>0{
                if $0.count > 0 {
                    self.httpManager.setTakeALookReplyComment(dongtai_id: self.model?.id ?? "", pid: self.replyModel?.id ?? "", ppid: "", content: $0) { message in
//                        self.view.showHUD(title: "评论成功，审核通过后展示")
                        self.loadData()
                        self.view.endEditing(true)
                        
                    } failure: { error in
                        self.view.showHUD(title: error)
                    }
                    
                }else{
                    self.view.showHUD(title: "内容不能为空")
                }
            }else{
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
            }
            
            
            
        }
        
    }
    
    @objc func tapHead() -> Void {
//        if self.superVCLive_uid == model?.live_uid ?? "" {
//
//        }else{
//            let userDetailControler = HWUserDetailController()
//            userDetailControler.live_uid = model?.live_uid ?? ""
//            self.navigationController?.pushViewController(userDetailControler, animated: true)
//        }
        
    }
    
    
    
    @objc func keyboardWillChangeFrameNotify(_ notify:NSNotification) -> Void {
        let duration = notify.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
        let keyboardFrame = notify.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        let transformY = keyboardFrame.origin.y - self.view.frame.size.height;
        UIView.animate(withDuration: duration) {
            
            if transformY == 0.0 {
                self.tempBgView.isHidden = true
                self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
                self.keyboardView.textField.placeholder = "请输入评论内容..."
                self.keyboardView.textField.text = ""
                self.replyModel = nil
            }else{
                self.tempBgView.isHidden = false
                if screenHeight < 812 {
                    self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
                    
                }else {
                    self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY + 34)
                }
            }
            
        }
    }
    
    @objc func closeKeyboard() -> Void {
        view.endEditing(true)
    }
    
    @objc private func navMoreButtonClick(){
        
        var title = "举报"
        if let uid = self.detailModel?.uid_des {
            if HWLocallyStoredData.getLoginUserID() == uid {
                title = "删除"
            }
        }
        // 创建一个 UIAlertController，样式为 actionSheet
        let actionSheet = UIAlertController(title: "", message: "更多选项", preferredStyle: .actionSheet)
                
        // 添加操作选项
        actionSheet.addAction(UIAlertAction(title: title, style: .default, handler: { _ in
            
            if title == "删除" {
                self.moreAction(type: 1, dongtai_id: self.detailModel?.id ?? "")
            }else{
                self.moreAction(type: 2, dongtai_id: self.detailModel?.id ?? "")
            }
        }))
        actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
                
        // 处理 iPad 中的 Action Sheet 弹出位置（必须指定）
        if let popoverController = actionSheet.popoverPresentationController {
            popoverController.sourceView = self.view
            popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
            popoverController.permittedArrowDirections = []
        }
                
        // 显示 Action Sheet
        self.present(actionSheet, animated: true, completion: nil)
    }
    
    private func moreAction(type: Int, dongtai_id: String){
        
        if type == 1 {
            //删除账号
            self.httpManager.deleteDynamic(dongtai_id: model?.id ?? "") { modelArr in
                
                self.deteleBlock?()
                self.navigationController?.popViewController(animated: true)
            } failure: { error in
                self.showHUDWithError(msg: error)
            }
        }else{
            //举报
            let reportVC = HWReportViewController()
            reportVC.dynamicID = dongtai_id
            self.present(reportVC, animated: true)
        }
    }
}
